﻿using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Utils
{
    public class IniHelper
    {
        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern long WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        private static extern int GetPrivateProfileInt(string section, string key, int defaultValue, string filePath);

 
        /// <summary>
        /// ini文件路径
        /// </summary>
        private const string _iniPathFile = "conf/common.ini";
 

        public static string IniPathFile
        {
            get
            {
                return _iniPathFile;
            }
        }

        /// <summary>
        /// 从Ini读取文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="iniPath"></param>
        /// <param name="retLen"></param>
        /// <returns></returns>
        public static string GetPrivateProfileString(string section, string key, string iniPath, int retLen)
        {
            var retSb = new StringBuilder(retLen);
            //var vpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, iniPath);
            GetPrivateProfileString(section, key, string.Empty, retSb, retLen, iniPath);
            return retSb.ToString();
        }

        /// <summary>
        /// 写入Key到Ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="iniPath"></param>
        public static void WriteKeyToIni(string section, string key, string value, string iniPath)
        {
            //var vpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, iniPath);
            WritePrivateProfileString(section, key, value, iniPath);
        }
    }
}